package com.hyp.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hyp.pojo.*;
import com.hyp.service.UserService;
import com.hyp.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j //显示日志消息
@RestController
@RequestMapping("/wx/")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/wxLogin")
    public Result wxLogin(@RequestBody Map<String, String> params) {
        String code = params.get("code");
        String appId = "wx165476a1ecebf9a6";
        String appSecret = "a7041191c25ab5e7be56277ee5e40000";
        String avatarUrl = params.get("avatarUrl");
        String nickName = params.get("nickName");
        Integer gender = Integer.valueOf(params.get("gender"));
        System.out.println("code为：" + code);
        // 构建请求URL
        String requestUrl = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appId, appSecret, code);
        System.out.println("url是是是" + requestUrl);
        // 使用OkHttp发送GET请求
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(requestUrl)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            System.out.println(response);
            // 解析响应
            String responseBody = response.body().string();
            System.out.println(responseBody);
            ObjectMapper objectMapper = new ObjectMapper();
            WeChatResponse weChatResponse = objectMapper.readValue(responseBody, WeChatResponse.class);

            String openId = weChatResponse.getOpenid();
            System.out.println("openid:????" + openId);
            String sessionKey = weChatResponse.getSession_key();

            // 在数据库中查找或创建用户
            User user = userService.findByWeChatOpenID(openId);
            if (user == null) {
                user = new User();
                user.setWeChatOpenID(openId);
                user.setNickName(nickName);
                user.setGender(gender);
                user.setAvatarUrl(avatarUrl);
                userService.save(user);
            }

            // 生成JWT
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", user.getUserId());
            String jwt = JwtUtils.generateJwt(claims);
            System.out.println("JWT是：：：："+jwt);
            return Result.success(jwt);
        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常，返回错误信息
            return Result.error("获取openid失败");
        }
    }

    @GetMapping("/userlist")
    public Result userlist() {
        List<User> userList = userService.list();
        return Result.success(userList);
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        userService.delete(id);
        return Result.success();
    }

    //查询回显
    @GetMapping("/userlist/{id}")
    public Result getById(@PathVariable Integer id){//@PathVariable获取路径ID
        User user = userService.getById(id);
        return Result.success(user);
    }

    @PutMapping("/updataUserinfo")
    public Result updataUserinfo(@RequestBody User user) {
        userService.updataUserinfo(user);
        return Result.success();
    }

    //解析jwt
    @GetMapping("/parseJwt/{jwt}")
    public Result parseJwt(@PathVariable String jwt) {
        String claims = String.valueOf(JwtUtils.parseJWT(jwt));
        return Result.success(claims);
    }
}